package org.jsola.hr.service.impl;

import org.jsola.core.Page;
import org.jsola.core.entity.BaseDO;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.ExampleKit;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dao.IEmpWorkDAO;
import org.jsola.hr.dto.EmpWorkAddDTO;
import org.jsola.hr.dto.EmpWorkDTO;
import org.jsola.hr.dto.EmpWorkUpdateDTO;
import org.jsola.hr.entity.EmpWorkDO;
import org.jsola.hr.query.EmpWorkQuery;
import org.jsola.hr.service.IEmpWorkService;
import org.jsola.hr.vo.EmpWorkListVO;
import org.jsola.hr.vo.EmpWorkVO;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhr
 */
@Service("hrEmpWorkServiceImpl")
public class EmpWorkServiceImpl implements IEmpWorkService {

    @Autowired
    private IEmpWorkDAO empWorkDAO;

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public EmpWorkVO save(EmpWorkAddDTO empWorkAddDTO, TokenUser tokenUser) {
        // 转DO
        EmpWorkDO empWorkDO = empWorkAddDTO.to(EmpWorkDO.class);

        // 校验员工和公司
        checkEmpAndCompany(empWorkDO.getEmpId(), empWorkDO.getCompanyId(), tokenUser.getSiteId());

        // 保存
        empWorkDO = save(empWorkDO, tokenUser.getSiteId(), tokenUser.getUserId());
        return empWorkDO.to(EmpWorkVO.class);
    }

    /**
     * 校验员工和公司
     *
     * @param empId     员工id
     * @param companyId 公司id
     * @param siteId    站点
     */
    private void checkEmpAndCompany(String empId, String companyId, String siteId) {
        ParamException.hasLength(empId, "员工id不能为空");
        ParamException.hasLength(companyId, "公司id不能为空");
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(EmpWorkUpdateDTO empWorkUpdateDTO, TokenUser tokenUser) {
        //转DO
        EmpWorkDO empWorkDO = empWorkUpdateDTO.to(EmpWorkDO.class);
        //根据主键更新，只更新非null值
        return updateByIdSelective(empWorkDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, String... empWorkIds) {
        return logicalDeleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) empWorkIds);
    }


    @Override
    public EmpWorkVO selectById(String empWorkId, String siteId) {
        EmpWorkDO empWorkDO = selectDOById(empWorkId, siteId);
        if (empWorkDO == null) {
            return null;
        }
        return empWorkDO.to(EmpWorkVO.class);
    }

    @Override
    public List<EmpWorkListVO> select(EmpWorkQuery empWorkQuery, String siteId) {
        List<EmpWorkDO> empWorkDOList = selectDO(empWorkQuery, siteId);
        if(CollectionUtils.isEmpty(empWorkDOList)) {
            return empWorkDOList == null ? null : new ArrayList<>();
        }
        return empWorkDOList.stream()
                .map(empWorkDO -> empWorkDO.to(EmpWorkListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(EmpWorkQuery empWorkQuery, String siteId) {
        Example example = buildExample(empWorkQuery,siteId);
        return empWorkDAO.selectCountByExample(example);
    }

    @Override
    public Page<EmpWorkListVO> selectPage(EmpWorkQuery empWorkQuery, String siteId) {
        Example example = buildExample(empWorkQuery,siteId);
        Page<EmpWorkDO> page = empWorkDAO.selectPageByExample(example,
                empWorkQuery.getPageNo(),
                empWorkQuery.getPageSize());

        return page.to(EmpWorkListVO.class);
    }

    @Override
    public EmpWorkDO selectDOById(String empWorkId, String siteId) {
        return listById(empWorkId, siteId);
    }

    @Override
    public List<EmpWorkDO> selectDO(EmpWorkQuery empWorkQuery, String siteId) {
        Example example = buildExample(empWorkQuery,siteId);
        return empWorkDAO.selectByExample(example);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public void deleteByCompanyId(String companyId, TokenUser tokenUser) {
        Example example = new Example(EmpWorkDO.class);
        example.and()
                .andEqualTo("companyId", companyId)
                .andEqualTo("valid", true)
                .andEqualTo("siteId", tokenUser.getSiteId());
        // 逻辑删除
        List<EmpWorkDO> list = empWorkDAO.selectByExample(example);
        String[] ids = list.stream()
                .map(BaseDO::getId).toArray(String[]::new);
        deleteByIds(tokenUser, ids);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public void publishEmpWorkList(List<EmpWorkDTO> empWorkList, String companyId, String empId, TokenUser tokenUser) {
        // 删除某个员工所有的
        deleteByEmpId(empId, tokenUser);

        if (CollectionUtils.isEmpty(empWorkList)) {
            return;
        }

        empWorkList.forEach(
                empWorkDTO -> {
                    empWorkDTO.setCompanyId(companyId);
                    empWorkDTO.setEmpId(empId);
                    // 新增
                    EmpWorkAddDTO empWorkAddDTO = empWorkDTO.to(EmpWorkAddDTO.class);
                    save(empWorkAddDTO, tokenUser);
                }
        );
    }

    @Override
    public List<EmpWorkDO> listByEmpId(String empId, String siteId) {
        Example example = new Example(EmpWorkDO.class);
        example.and()
                .andEqualTo("empId", empId)
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        example.orderBy("gmtCreate");
        //
        return empWorkDAO.selectByExample(example);
    }

    /**
     * 删除某个员工所有的
     *
     * @param empId     员工id
     * @param tokenUser 当前用户
     */
    private void deleteByEmpId(String empId, TokenUser tokenUser) {

        List<EmpWorkDO> list = listByEmpId(empId, tokenUser.getSiteId());
        String[] ids = list.stream()
                .map(BaseDO::getId).toArray(String[]::new);
        deleteByIds(tokenUser, ids);
    }


    /**
     * 根据查询参数，构建example

     * @param empWorkQuery 查询参数
     * @param siteId 所属站点id
     * @return example
     */
    private Example buildExample(EmpWorkQuery empWorkQuery, String siteId) {
        Example example = new Example(EmpWorkDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        if (empWorkQuery.getEmpId() != null) {
            example.and().andLike("empId", "%" + empWorkQuery.getEmpId() + "%");
        }
        if (empWorkQuery.getCompany() != null) {
            example.and().andLike("company", "%" + empWorkQuery.getCompany() + "%");
        }
        if (empWorkQuery.getPosition() != null) {
            example.and().andLike("position", "%" + empWorkQuery.getPosition() + "%");
        }
        if (empWorkQuery.getStartTimeStart() != null &&
                empWorkQuery.getStartTimeEnd() != null) {
            example.and().andBetween("startTime", empWorkQuery.getStartTimeStart(),
                    empWorkQuery.getStartTimeEnd());
        }
        if (empWorkQuery.getEndTimeStart() != null &&
                empWorkQuery.getEndTimeEnd() != null) {
            example.and().andBetween("endTime", empWorkQuery.getEndTimeStart(),
                    empWorkQuery.getEndTimeEnd());
        }
        if (empWorkQuery.getLeaveReason() != null) {
            example.and().andLike("leaveReason", "%" + empWorkQuery.getLeaveReason() + "%");
        }
        if (empWorkQuery.getWitName() != null) {
            example.and().andLike("witName", "%" + empWorkQuery.getWitName() + "%");
        }
        if (empWorkQuery.getWitPhone() != null) {
            example.and().andLike("witPhone", "%" + empWorkQuery.getWitPhone() + "%");
        }
        if (empWorkQuery.getCompanyId() != null) {
            example.and().andEqualTo("companyId", empWorkQuery.getCompanyId());
        }
        if (empWorkQuery.getGmtCreateStart() != null &&
                empWorkQuery.getGmtCreateEnd() != null) {
            example.and().andBetween("gmtCreate", empWorkQuery.getGmtCreateStart(),
                    empWorkQuery.getGmtCreateEnd());
        }
        if (empWorkQuery.getCreateUserId() != null) {
            example.and().andLike("createUserId", "%" + empWorkQuery.getCreateUserId() + "%");
        }
        if (empWorkQuery.getGmtModifiedStart() != null &&
                empWorkQuery.getGmtModifiedEnd() != null) {
            example.and().andBetween("gmtModified", empWorkQuery.getGmtModifiedStart(),
                    empWorkQuery.getGmtModifiedEnd());
        }
        if (empWorkQuery.getModifiedUserId() != null) {
            example.and().andLike("modifiedUserId", "%" + empWorkQuery.getModifiedUserId() + "%");
        }
        // 排序
        ExampleKit.setExampleOrder(example,empWorkQuery.getOrders());
        return example;
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public Integer deleteEmpWork(TokenUser tokenUser, String empWorkId){
        return empWorkDAO.deleteByPrimaryKey(empWorkId);
    }
}




